package cn.flying.cloud.base.core.configuration;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

/**
 * 注解@Async使用的异步任务的线程池
 *
 * @author: admin
 * @date: 2025年03月19日 15:32
 * @version: 1.0
 */
@EnableAsync
@Configuration(proxyBeanMethods = false)
//@ConditionalOnClass(value = ExecutorConfigurer.class)
public class FtAsyncExecutorConfigurer implements AsyncConfigurer {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        int core = Runtime.getRuntime().availableProcessors() * 2;
        //配置核心线程数
        executor.setCorePoolSize(core);
        //配置最大线程数
        executor.setMaxPoolSize(core * 4);
        //配置队列大小
        executor.setQueueCapacity(200);
        executor.setKeepAliveSeconds(60);
        //配置线程池中的线程的名称前缀
        executor.setThreadNamePrefix("Ft-async-");
        executor.setAwaitTerminationSeconds(60);
        // rejection-policy：当pool已经达到max size的时候，如何处理新任务
        // CALLER_RUNS：不在新线程中执行任务，而是有调用者所在的线程来执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //增加MDC的线程池修饰类
        executor.setTaskDecorator(new MDCTaskDecorator());
        //执行初始化
        executor.initialize();
        if (logger.isDebugEnabled()) {
            logger.debug("自定义异步任务线程池配置完成！");
        }
        return executor;
    }

}